package com.zhao.fishingguideserver.controller;

import com.zhao.fishingguideserver.POJO.Cart;
import com.zhao.fishingguideserver.POJO.Result;
import com.zhao.fishingguideserver.service.CartService;
import com.zhao.fishingguideserver.utils.ThreadLocalUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.List;
import java.util.Map;
// 关键：添加/api前缀，与前端请求路径（/api/cart/**）一致
@RestController
@RequestMapping("/cart")
public class CartController {
    @Autowired
    private CartService cartService;
    /**
     * 添加购物车（无需前端传userId，从ThreadLocal获取）
     */
    @PostMapping("/add")
    public Result<String> addCart(
            @RequestParam Long productId,
            @RequestParam Integer quantity
    ) {
        Map<String, Object> claims = ThreadLocalUtil.get();
        Long userId = Long.parseLong(claims.get("id").toString());
        String msg = cartService.addCart(userId, productId, quantity); // 接收提示信息
        return Result.success(msg); // 返回提示信息给前端
    }
    /**
     * 查询购物车列表（无需前端传userId）
     */
    @GetMapping("/list")
    public Result<List<Cart>> listCart() {
        Map<String, Object> claims = ThreadLocalUtil.get();
        if (claims == null || claims.get("id") == null) {
            return Result.error("用户未登录");
        }
        Long userId = Long.parseLong(claims.get("id").toString());

        List<Cart> carts = cartService.listCart(userId);
        return Result.success(carts);
    }
    /**
     * 修改商品数量（无变化）
     */
    @PostMapping("/updateQuantity")
    public Result<Void> updateQuantity(
            @RequestParam Long cartId,
            @RequestParam Integer quantity
    ) {
        cartService.updateQuantity(cartId, quantity);
        return Result.success();
    }
    /**
     * 删除商品（无变化）
     */
    @PostMapping("/delete")
    public Result<Void> deleteCart(@RequestParam Long cartId) {
        cartService.deleteCart(cartId);
        return Result.success();
    }
    /**
     * 切换选中状态（无变化）
     */
    @PostMapping("/toggleSelect")
    public Result<Void> toggleSelect(
            @RequestParam Long cartId,
            @RequestParam Integer isSelected
    ) {
        cartService.toggleSelect(cartId, isSelected == 1);
        return Result.success();
    }
    /**
     * 全选 / 取消全选（无需前端传userId）
     */
    @PostMapping("/selectAll")
    public Result<Void> selectAll(@RequestParam Integer isSelected) {
        Map<String, Object> claims = ThreadLocalUtil.get();
        Long userId = Long.parseLong(claims.get("id").toString());

        cartService.selectAll(userId, isSelected == 1);
        return Result.success();
    }
    /**
     * 批量删除（无变化，接收前端传的id数组）
     */
    @PostMapping("/batchDelete")
    public Result<Void> batchDelete(@RequestBody List<Long> cartIds) {
        cartService.batchDelete(cartIds);
        return Result.success();
    }
}